/*
 * Copyright 2010-2013, David George, Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.magneato.mvc;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.magneato.dto.Point;
import org.magneato.utils.parsers.GpxParser;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.ModelAndView;

/**
 * Transforms a geodata file (the type of information that comes from a GPS
 * device) into a coordinate set that can be used by a mapping application.
 * 
 * @author David George
 */
@Controller
public class GeoController implements ServletContextAware {
	ServletContext servletContext;
	private final Log _logger = LogFactory.getLog(GeoController.class);

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	/**
	 * Servlet to convert GPX file (gpx... etc) to a Javascript data type for display in Google maps
	 * 
	 * @param response
	 * @param url
	 * @param type
	 * @return Spring Model and View
	 * @throws IOException
	 * @throws Exception
	 */
	@RequestMapping(value = "/getCoords.do")
	public ModelAndView uploadFile(HttpServletResponse response, String url,
			String format) {
		// save attachments object as xml
		if (url.charAt(0) == '/') {
			url = "file://" + servletContext.getRealPath(url);
		}
		URL geoFile;
		ArrayList<Point> points = null;
		try {
			geoFile = new URL(url);

			URLConnection con = geoFile.openConnection();

			GpxParser gpxParser = new GpxParser();
			gpxParser.read(con.getInputStream());

			points = gpxParser.getPoints();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			_logger.error(e.getMessage());
		}
		response.setContentType("text/xml");
		return new ModelAndView("sys/geodata", "points", points);
	}
}